package com.custom.BluetoothClient;

import android.bluetooth.BluetoothAdapter;
import android.bluetooth.BluetoothDevice;
import android.bluetooth.BluetoothSocket;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;


import androidx.appcompat.app.AppCompatActivity;

import java.io.IOException;
import java.io.OutputStream;
import java.util.UUID;
//客户端

public class MainActivity extends AppCompatActivity {
    private Button button;
    private EditText editText;
    BluetoothAdapter blueAdapter;
    private BluetoothSocket socket;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        button = findViewById(R.id.btn);
        editText = findViewById(R.id.edt);
        //对方蓝牙的地址
        final String address = "98:9C:57:18:82:30";
        blueAdapter = BluetoothAdapter.getDefaultAdapter();
        //通过对方蓝牙的地址，可以得到远程蓝牙对象
        final BluetoothDevice remoteDevice = blueAdapter.getRemoteDevice(address);
        //创建远程客户端套接字对象
        try {

            socket = remoteDevice.createRfcommSocketToServiceRecord(UUID.fromString("fa87c0d0-afac-11de-8a39-0800200c9a66"));
            //开始连接
            socket.connect();
        } catch (IOException e) {
            e.printStackTrace();
        }
        button.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                try {
                    final String msg = editText.getText().toString();  //获取要发送的信息内容
                    //写入数据
                    OutputStream os = socket.getOutputStream();
                    os.write(msg.getBytes());
                    Log.e("msg", msg);
                } catch (Exception e) {
                    e.printStackTrace();
                }
            }
        });

    }
}
